package com.naiterui.ehp.bs.ds.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.naiterui.ehp.bp.security.utils.BaseJwtUser;
import com.naiterui.ehp.bp.security.utils.SecurityUtils;
import java.util.Date;
import org.apache.ibatis.reflection.MetaObject;

/**
 * 公共字段填充
 *
 * @author 王泽浩
 * @date 2018/4/16 上午10:20
 * @since 1.0.0
 */
public class SaveOrUpdateMetaObjectHandler implements MetaObjectHandler {

  @Override
  public void insertFill(MetaObject metaObject) {
    Object createdAt = this.getFieldValByName("createdAt", metaObject);
    if (createdAt == null) {
      this.setFieldValByName("createdAt", new Date(), metaObject);
    }
    Object createdBy = this.getFieldValByName("createdBy", metaObject);
    if (createdBy == null) {
      this.setFieldValByName("createdBy", this.getModifyUserName(), metaObject);
    }
  }

  @Override
  public void updateFill(MetaObject metaObject) {
    this.setFieldValByName("changedAt", new Date(), metaObject);
    this.setFieldValByName("changedBy", this.getModifyUserName(), metaObject);
  }

  /**
   * 获取当前记录操作人
   */
  private String getModifyUserName() {
    String modifyUserName;
    BaseJwtUser user = null;
    try {
      user = SecurityUtils.getCurrentUser();
    } catch (Exception ignored) {

    }
    if (user == null) {
      modifyUserName = "system";
    } else {
      modifyUserName = user.getUsername();
    }
    return modifyUserName;
  }
}
